package com.hkzhao.shixun.common.utils;

import com.hkzhao.shixun.mbg.model.Prize;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * <h3>j2ee</h3>
 * <p>抽奖工具实现</p>
 *
 * @author : hkzhao
 * @date : 2020-06-06 11:21
 **/
@Component
public class DrawsLotteryUtil {
    public Prize draws(List<Prize> list){
        Collections.sort(list, new Comparator<Prize>() {
            @Override
            public int compare(Prize o1, Prize o2) {
                return (o1.getNums()-o1.getHaslotterynum())-(o2.getNums()-o2.getHaslotterynum());
            }
        });
        List<Double> probsList = getProbs(list);
        if(probsList.size()==0){
            return null;
        }
        double random = Math.random();
        double current=0;
        for (int i=0;i<probsList.size();i++)
        {
            current+=probsList.get(i);
            if (current>=random) return list.get(i);
        }
        return null;
    }
    private List<Double> getProbs(List<Prize> list){
        double total = 0;
        for (Prize p : list){
            total += p.getNums()-p.getHaslotterynum();
        }
        List<Double> probsList = new ArrayList<>();
        if(total==0)
        {
            return probsList;
        }
        for(Prize p: list) {
            probsList.add((p.getNums() - p.getHaslotterynum()) / total);
        }
        return probsList;
    }
}
